package com.example.yichuangyun.utils;

import java.io.File;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.regex.Pattern;

public class DateUtil {
//    protected static Log logger = LogFactory.getLog(DateUtil.class);

    // 格式：年－月－日 小时：分钟：秒
    public static final String FORMAT_ONE = "yyyy-MM-dd HH:mm:ss";

    // 格式：年－月－日 小时：分钟
    public static final String FORMAT_TWO = "yyyy-MM-dd HH:mm";

    // 格式：年月日 小时分钟秒
    public static final String FORMAT_THREE = "yyyyMMdd-HHmmss";
    // 格式：分秒
    public static final String FORMAT_FOUR = "HH:mm";

    // 格式：年月日
    public static final String FORMAT_YEAR_MONTH_DAY = "yyyyMMdd";

    // 格式：年－月－日
    public static final String LONG_DATE_FORMAT = "yyyy-MM-dd";

    // 格式：月－日
    public static final String SHORT_DATE_FORMAT = "MM-dd";

    // 格式：小时：分钟：秒
    public static final String LONG_TIME_FORMAT = "HH:mm:ss";

    //格式：年-月
    public static final String MONTG_DATE_FORMAT = "yyyy-MM";
    public static final String MONTG_DATE_FORMAT_C = "yyyy年MM月";
    public static final String MONTG_DATE_FORMAT_WITHOUT_HYPHEN = "yyyyMM";

    // 年的加减
    public static final int SUB_YEAR = Calendar.YEAR;

    // 月加减
    public static final int SUB_MONTH = Calendar.MONTH;

    // 天的加减
    public static final int SUB_DAY = Calendar.DATE;

    // 小时的加减
    public static final int SUB_HOUR = Calendar.HOUR;

    // 分钟的加减
    public static final int SUB_MINUTE = Calendar.MINUTE;

    // 秒的加减
    public static final int SUB_SECOND = Calendar.SECOND;

    static final String dayNames[] = {"星期日", "星期一", "星期二", "星期三", "星期四",
            "星期五", "星期六"};

    @SuppressWarnings("unused")
    private static final SimpleDateFormat timeFormat = new SimpleDateFormat(
            "yyyy-MM-dd HH:mm:ss");


    /**
     * 用于显示时间
     */
    public static final String TODAY = "今天";
    public static final String YESTERDAY = "昨天";
    public static final String TOMORROW = "明天";
    public static final String BEFORE_YESTERDAY = "前天";
    public static final String AFTER_TOMORROW = "后天";

    public DateUtil() {
    }

    /**
     * 把符合日期格式的字符串转换为日期类型
     *
     * @param dateStr
     * @return
     */
    public static Date stringtoDate(String dateStr, String format) {
        Date d = null;
        SimpleDateFormat formater = new SimpleDateFormat(format);
        try {
            formater.setLenient(false);
            d = formater.parse(dateStr);
        } catch (Exception e) {
            // log.error(e);
            d = null;
        }
        return d;
    }

    /**
     * 把符合日期格式的字符串转换为日期类型
     */
    public static Date stringtoDate(String dateStr, String format,
                                    ParsePosition pos) {
        Date d = null;
        SimpleDateFormat formater = new SimpleDateFormat(format);
        try {
            formater.setLenient(false);
            d = formater.parse(dateStr, pos);
        } catch (Exception e) {
            d = null;
        }
        return d;
    }

    /**
     * 把日期转换为字符串
     *
     * @param date
     * @return
     */
    public static String dateToString(Date date, String format) {
        String result = "";
        SimpleDateFormat formater = new SimpleDateFormat(format);
        try {
            result = formater.format(date);
        } catch (Exception e) {
            // log.error(e);
        }
        return result;
    }

    /**
     * 获取当前时间的指定格式
     *
     * @param format
     * @return
     */
    public static String getCurrDate(String format) {
        return dateToString(new Date(), format);
    }

    /**
     * @param dateStr
     * @param amount
     * @return
     */
    public static String dateSub(int dateKind, String dateStr, int amount) {
        Date date = stringtoDate(dateStr, FORMAT_ONE);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(dateKind, amount);
        return dateToString(calendar.getTime(), FORMAT_ONE);
    }

    /*将字符串转为时间戳*/
    public static long getStringToDate(String time) {
        SimpleDateFormat sdf = new SimpleDateFormat(LONG_DATE_FORMAT);
        Date date = new Date();
        try {
            date = sdf.parse(time);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return date.getTime();
    }

    /**
     * 两个日期相减
     *
     * @param firstTime
     * @param secTime
     * @return 相减得到的秒数
     */
    public static long timeSub(String firstTime, String secTime) {
        long first = stringtoDate(firstTime, FORMAT_ONE).getTime();
        long second = stringtoDate(secTime, FORMAT_ONE).getTime();
        return (second - first) / 1000;
    }

    /**
     * 获得某月的天数
     *
     * @param year  int
     * @param month int
     * @return int
     */
    public static int getDaysOfMonth(String year, String month) {
        int days = 0;
        if (month.equals("1") || month.equals("3") || month.equals("5")
                || month.equals("7") || month.equals("8") || month.equals("10")
                || month.equals("12")) {
            days = 31;
        } else if (month.equals("4") || month.equals("6") || month.equals("9")
                || month.equals("11")) {
            days = 30;
        } else {
            if ((Integer.parseInt(year) % 4 == 0 && Integer.parseInt(year) % 100 != 0)
                    || Integer.parseInt(year) % 400 == 0) {
                days = 29;
            } else {
                days = 28;
            }
        }

        return days;
    }

    /**
     * 获取某年某月的天数
     *
     * @param year  int
     * @param month int 月份[1-12]
     * @return int
     */
    public static int getDaysOfMonth(int year, int month) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month - 1, 1);
        return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
    }

    /**
     * 获得当前日期
     *
     * @return int
     */
    public static int getToday() {
        Calendar calendar = Calendar.getInstance();
        return calendar.get(Calendar.DATE);
    }

    /**
     * 获得当前月份
     *
     * @return int
     */
    public static int getToMonth() {
        Calendar calendar = Calendar.getInstance();
        return calendar.get(Calendar.MONTH) + 1;
    }

    /**
     * 获得当前年份
     *
     * @return int
     */
    public static int getToYear() {
        Calendar calendar = Calendar.getInstance();
        return calendar.get(Calendar.YEAR);
    }

    /**
     * 返回日期的天
     *
     * @param date Date
     * @return int
     */
    public static int getDay(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.DATE);
    }

    /**
     * 返回日期的年
     *
     * @param date Date
     * @return int
     */
    public static int getYear(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.YEAR);
    }

    /**
     * 返回日期的月份，1-12
     *
     * @param date Date
     * @return int
     */
    public static int getMonth(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.MONTH) + 1;
    }

    /**
     * 计算两个日期相差的天数，如果date2 > date1 返回正数，否则返回负数
     *
     * @param date1 Date
     * @param date2 Date
     * @return long
     */
    public static long dayDiff(Date date1, Date date2) {
        return (date2.getTime() - date1.getTime()) / 86400000;
    }

    /**
     * 比较两个日期的年差
     *
     * @param before
     * @param after
     * @return
     */
    public static int yearDiff(String before, String after) {
        Date beforeDay = stringtoDate(before, LONG_DATE_FORMAT);
        Date afterDay = stringtoDate(after, LONG_DATE_FORMAT);
        return getYear(afterDay) - getYear(beforeDay);
    }

    /**
     * 比较指定日期与当前日期的差
     *
     * @param after
     * @return
     */
    public static int yearDiffCurr(String after) {
        Date beforeDay = new Date();
        Date afterDay = stringtoDate(after, LONG_DATE_FORMAT);
        return getYear(beforeDay) - getYear(afterDay);
    }

    /**
     * 比较指定日期与当前日期的差
     *
     * @param before
     * @return
     * @author chenyz
     */
    public static long dayDiffCurr(String before) {
        Date currDate = DateUtil.stringtoDate(getCurrentDay(), LONG_DATE_FORMAT);
        Date beforeDate = stringtoDate(before, LONG_DATE_FORMAT);
        return (currDate.getTime() - beforeDate.getTime()) / 86400000;
    }

    /**
     * 获取10位的utc时间
     *
     * @return
     */
    public static String date2utcStr() {
        Date dateStr = new Date();
        String retStr = "";
        //  Date date = parse(dateStr);
        if (dateStr != null) {
            long miliSeconds = dateStr.getTime();
            retStr = String.valueOf(miliSeconds / 1000L);
        }
        return retStr;
    }

    /**
     * 获取每月的第一周
     *
     * @param year
     * @param month
     * @return
     * @author chenyz
     */
    public static int getFirstWeekdayOfMonth(int year, int month) {
        Calendar c = Calendar.getInstance();
        c.setFirstDayOfWeek(Calendar.SATURDAY); // 星期天为第一天
        c.set(year, month - 1, 1);
        return c.get(Calendar.DAY_OF_WEEK);
    }

    /**
     * 获取每月的最后一周
     *
     * @param year
     * @param month
     * @return
     * @author chenyz
     */
    public static int getLastWeekdayOfMonth(int year, int month) {
        Calendar c = Calendar.getInstance();
        c.setFirstDayOfWeek(Calendar.SATURDAY); // 星期天为第一天
        c.set(year, month - 1, getDaysOfMonth(year, month));
        return c.get(Calendar.DAY_OF_WEEK);
    }

    /**
     * 获得当前日期字符串，格式"yyyy_MM_dd_HH_mm_ss"
     *
     * @return
     */
    public static String getCurrent() {
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;
        int day = cal.get(Calendar.DAY_OF_MONTH);
        int hour = cal.get(Calendar.HOUR_OF_DAY);
        int minute = cal.get(Calendar.MINUTE);
        int second = cal.get(Calendar.SECOND);
        StringBuffer sb = new StringBuffer();
        sb.append(year).append("_").append(addzero(month, 2))
                .append("_").append(addzero(day, 2)).append("_")
                .append(addzero(hour, 2)).append("_").append(
                        addzero(minute, 2)).append("_").append(
                        addzero(second, 2));
        return sb.toString();
    }

    /**
     * 获得当前日期字符串，格式"yyyy-MM-dd HH:mm:ss"
     *
     * @return
     */
    public static String getNow() {
        Calendar today = Calendar.getInstance();
        return dateToString(today.getTime(), FORMAT_ONE);
    }

    public static String getNowTime() {
        Calendar today = Calendar.getInstance();
        return dateToString(today.getTime(), FORMAT_TWO);
    }


    public static String getNowYMD() {
        Calendar today = Calendar.getInstance();
        return dateToString(today.getTime(), LONG_DATE_FORMAT);
    }

    /**
     * 根据生日获取星座
     *
     * @param birth YYYY-mm-dd
     * @return
     */
    public static String getAstro(String birth) {
        if (!isDate(birth)) {
            birth = "2000" + birth;
        }
        if (!isDate(birth)) {
            return "";
        }
        int month = Integer.parseInt(birth.substring(birth.indexOf("-") + 1,
                birth.lastIndexOf("-")));
        int day = Integer.parseInt(birth.substring(birth.lastIndexOf("-") + 1));
        String s = "魔羯水瓶双鱼牡羊金牛双子巨蟹狮子处女天秤天蝎射手魔羯";
        int[] arr = {20, 19, 21, 21, 21, 22, 23, 23, 23, 23, 22, 22};
        int start = month * 2 - (day < arr[month - 1] ? 2 : 0);
        return s.substring(start, start + 2) + "座";
    }

    /**
     * 判断日期是否有效,包括闰年的情况
     *
     * @param date YYYY-mm-dd
     * @return
     */
    public static boolean isDate(String date) {
        StringBuffer reg = new StringBuffer(
                "^((\\d{2}(([02468][048])|([13579][26]))-?((((0?");
        reg.append("[13578])|(1[02]))-?((0?[1-9])|([1-2][0-9])|(3[01])))");
        reg.append("|(((0?[469])|(11))-?((0?[1-9])|([1-2][0-9])|(30)))|");
        reg.append("(0?2-?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][12");
        reg.append("35679])|([13579][01345789]))-?((((0?[13578])|(1[02]))");
        reg.append("-?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))");
        reg.append("-?((0?[1-9])|([1-2][0-9])|(30)))|(0?2-?((0?[");
        reg.append("1-9])|(1[0-9])|(2[0-8]))))))");
        Pattern p = Pattern.compile(reg.toString());
        return p.matcher(date).matches();
    }

    /**
     * 取得指定日期过 months 月后的日期 (当 months 为负数表示指定月之前);
     *
     * @param date   日期 为null时表示当天
     * @param months 相加(相减)的月数
     */
    public static Date nextMonth(Date date, int months) {
        Calendar cal = Calendar.getInstance();
        if (date != null) {
            cal.setTime(date);
        }
        cal.add(Calendar.MONTH, months);
        return cal.getTime();
    }

    /**
     * 取得指定日期过 day 天后的日期 (当 day 为负数表示指日期之前);
     *
     * @param date 日期 为null时表示当天
     * @param day  相加(相减)的月数
     */
    public static Date nextDay(Date date, int day) {
        Calendar cal = Calendar.getInstance();
        if (date != null) {
            cal.setTime(date);
        }
        cal.add(Calendar.DAY_OF_YEAR, day);
        return cal.getTime();
    }

    /**
     * 取得距离今天 day 日的日期
     *
     * @param day
     * @param format
     * @return
     * @author chenyz
     */
    public static String nextDay(int day, String format) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        cal.add(Calendar.DAY_OF_YEAR, day);
        return dateToString(cal.getTime(), format);
    }

    /**
     * 取得指定日期过 day 周后的日期 (当 day 为负数表示指定月之前)
     *
     * @param date 日期 为null时表示当天
     */
    public static Date nextWeek(Date date, int week) {
        Calendar cal = Calendar.getInstance();
        if (date != null) {
            cal.setTime(date);
        }
        cal.add(Calendar.WEEK_OF_MONTH, week);
        return cal.getTime();
    }

    /**
     * 获取当前的年月日(yyyyMMdd)
     */
    public static String getCurrentYearMonthDay() {
        return DateUtil.dateToString(new Date(), DateUtil.FORMAT_YEAR_MONTH_DAY);
    }

    /**
     * 获取当前的日期(yyyy-MM-dd)
     */
    public static String getCurrentDay() {

        return DateUtil.dateToString(new Date(), DateUtil.LONG_DATE_FORMAT);
    }

    /**
     * 获取当天的前30天(yyyy-MM-dd)
     */
    public static String getLastThirtyDay(String DateStr) {
        String minDateStr = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calc = Calendar.getInstance();
        try {
            calc.setTime(sdf.parse(DateStr));
            calc.add(calc.DATE, -30);
            Date minDate = calc.getTime();
            minDateStr = sdf.format(minDate);
            System.out.println("minDateStr:" + minDateStr);//minDateStr:2017-01-09   正确！！！！
        } catch (ParseException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        return minDateStr;
    }

    /**
     * 获取当前的日期(yyyy-MM-dd)
     */
    public static String getCurrentMonth() {
        return DateUtil.dateToString(new Date(), DateUtil.MONTG_DATE_FORMAT);
    }

    public static String getCurrentMonthC() {
        return DateUtil.dateToString(new Date(), DateUtil.MONTG_DATE_FORMAT_C);
    }

    /**
     * 根据当前日期获得上周的日期区间（本周周一和周日日期
     *
     * @param format
     * @return
     */
    public static String getThisWeekTimeIntervalStart(String format) {
        Calendar calendarBegin = Calendar.getInstance(Locale.CHINA);
        calendarBegin.setFirstDayOfWeek(Calendar.MONDAY);
        calendarBegin.setTimeInMillis(System.currentTimeMillis());
        //周一
        calendarBegin.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);

        Calendar calendarEnd = Calendar.getInstance(Locale.CHINA);
        calendarEnd.setFirstDayOfWeek(Calendar.MONDAY);
        calendarEnd.setTimeInMillis(System.currentTimeMillis());
        //周日
        calendarEnd.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
        return dateToString(calendarBegin.getTime(), format);
    }

    public static String getThisWeekTimeIntervalEnd(String format) {
        Calendar calendarBegin = Calendar.getInstance(Locale.CHINA);
        calendarBegin.setFirstDayOfWeek(Calendar.MONDAY);
        calendarBegin.setTimeInMillis(System.currentTimeMillis());
        //周一
        calendarBegin.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);

        Calendar calendarEnd = Calendar.getInstance(Locale.CHINA);
        calendarEnd.setFirstDayOfWeek(Calendar.MONDAY);
        calendarEnd.setTimeInMillis(System.currentTimeMillis());
        //周日
        calendarEnd.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
        return dateToString(calendarEnd.getTime(), format);
    }

    /**
     * 根据当前日期获得上周的日期区间（上周周一和周日日期
     *
     * @param format
     * @return
     */
    public static String getLastWeekTimeIntervalStart(String format) {
        Date date = new Date();
        Calendar calendarBegin = Calendar.getInstance();
        calendarBegin.setTime(date);
        //判断当前日期是否为周末，因为周末是本周第一天，如果不向后推迟一天的到的将是下周一的零点，而不是本周周一零点
        if (1 == calendarBegin.get(Calendar.DAY_OF_WEEK)) {
            calendarBegin.add(Calendar.DATE, -1);
        }
        //时间减去7天
        calendarBegin.add(Calendar.DAY_OF_MONTH, -7);
        calendarBegin.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);

        Calendar calendarEnd = Calendar.getInstance();
        calendarEnd.setTime(date);
        if (1 == calendarEnd.get(Calendar.DAY_OF_WEEK)) {
            calendarEnd.add(Calendar.DATE, -1);
        }
        calendarEnd.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
        return dateToString(calendarBegin.getTime(), format);
    }

    /**
     * 根据当前日期获得上周的日期区间（上周周一和周日日期
     *
     * @param format
     * @return
     */
    public static String getLastWeekTimeIntervalEnd(String format) {
        Date date = new Date();
        Calendar calendarBegin = Calendar.getInstance();
        calendarBegin.setTime(date);
        //判断当前日期是否为周末，因为周末是本周第一天，如果不向后推迟一天的到的将是下周一的零点，而不是本周周一零点
        if (1 == calendarBegin.get(Calendar.DAY_OF_WEEK)) {
            calendarBegin.add(Calendar.DATE, -1);
        }
        //时间减去7天
        calendarBegin.add(Calendar.DAY_OF_MONTH, -7);
        calendarBegin.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);

        Calendar calendarEnd = Calendar.getInstance();
        calendarEnd.setTime(date);
        if (1 == calendarEnd.get(Calendar.DAY_OF_WEEK)) {
            calendarEnd.add(Calendar.DATE, -1);
        }
        calendarEnd.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
        return dateToString(calendarEnd.getTime(), format);
    }

    /**
     * 本月份的第一天
     *
     * @param date
     * @return
     */
    public static String getSupportBeginDayofMonth(Date date) {
        date.getTime();
        Calendar startDate = Calendar.getInstance();
        startDate.setTime(date);
        startDate.set(Calendar.DAY_OF_MONTH, 1);
        startDate.set(Calendar.HOUR_OF_DAY, 0);
        startDate.set(Calendar.MINUTE, 0);
        startDate.set(Calendar.SECOND, 0);
        startDate.set(Calendar.MILLISECOND, 0);
        Date firstDate = startDate.getTime();
        return DateUtil.dateToString(firstDate, DateUtil.LONG_DATE_FORMAT);

    }

    /**
     * 本月份的最后一天
     *
     * @param date
     * @return
     */
    public static String getSupportEndDayofMonth(Date date) {
        Calendar startDate = Calendar.getInstance();
        startDate.setTime(date);
        startDate.set(Calendar.DAY_OF_MONTH, startDate.getActualMaximum(Calendar.DAY_OF_MONTH));
        startDate.set(Calendar.HOUR_OF_DAY, 23);
        startDate.set(Calendar.MINUTE, 59);
        startDate.set(Calendar.SECOND, 59);
        startDate.set(Calendar.MILLISECOND, 999);
        Date firstDate = startDate.getTime();
        return DateUtil.dateToString(firstDate, DateUtil.LONG_DATE_FORMAT);
    }


    /**
     * 获取当前的日期(yyyy-MM)
     */
    public static String getCurrentYearAndMonth() {
        return DateUtil.dateToString(new Date(), DateUtil.MONTG_DATE_FORMAT);
    }

    /**
     * 获取当前的日期(yyyyMM)
     */
    public static String getCurrentYearAndMonthWithoutHyphen() {
        return DateUtil.dateToString(new Date(), DateUtil.MONTG_DATE_FORMAT_WITHOUT_HYPHEN);
    }

    /**
     * 获取昨天的日期
     *
     * @return
     */
    public static String befoDay() {
        return befoDay(DateUtil.LONG_DATE_FORMAT);
    }

    /**
     * 根据时间类型获取昨天的日期
     *
     * @param format
     * @return
     * @author chenyz
     */
    public static String befoDay(String format) {
        return DateUtil.dateToString(DateUtil.nextDay(new Date(), -1), format);
    }

    /**
     * 获取明天的日期
     */
    public static String afterDay() {
        return DateUtil.dateToString(DateUtil.nextDay(new Date(), 1),
                DateUtil.LONG_DATE_FORMAT);
    }

    /**
     * 取得当前时间距离1900/1/1的天数
     *
     * @return
     */
    public static int getDayNum() {
        int daynum = 0;
        GregorianCalendar gd = new GregorianCalendar();
        Date dt = gd.getTime();
        GregorianCalendar gd1 = new GregorianCalendar(1900, 1, 1);
        Date dt1 = gd1.getTime();
        daynum = (int) ((dt.getTime() - dt1.getTime()) / (24 * 60 * 60 * 1000));
        return daynum;
    }

    /**
     * getDayNum的逆方法(用于处理Excel取出的日期格式数据等)
     *
     * @param day
     * @return
     */
    public static Date getDateByNum(int day) {
        GregorianCalendar gd = new GregorianCalendar(1900, 1, 1);
        Date date = gd.getTime();
        date = nextDay(date, day);
        return date;
    }

    /**
     * 针对yyyy-MM-dd HH:mm:ss格式,显示yyyymmdd
     */
    public static String getYmdDateCN(String datestr) {
        if (datestr == null)
            return "";
        if (datestr.length() < 10)
            return "";
        StringBuffer buf = new StringBuffer();
        buf.append(datestr.substring(0, 4)).append(datestr.substring(5, 7))
                .append(datestr.substring(8, 10));
        return buf.toString();
    }

    /**
     * 获取本月第一天
     *
     * @param format
     * @return
     */
    public static String getFirstDayOfMonth(String format) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DATE, 1);
        return dateToString(cal.getTime(), format);
    }

    /**
     * 获取本月最后一天
     *
     * @param format
     * @return
     */
    public static String getLastDayOfMonth(String format) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DATE, 1);
        cal.add(Calendar.MONTH, 1);
        cal.add(Calendar.DATE, -1);
        return dateToString(cal.getTime(), format);
    }

    /**
     * 获取上月第一天
     */
    public static String getFirstDayOfLastMonth(String format) {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MONTH, -1);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        return dateToString(cal.getTime(), format);
    }

    /**
     * 获取上月最后一天
     */
    public static String getLastDayOfLastMonth(String format) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DAY_OF_MONTH, 1);
        cal.add(Calendar.DATE, -1);
        return dateToString(cal.getTime(), format);
    }

    /**
     * 获取上上月第一天
     */
    public static String getFirstDayOfLastTwoMonth(String format) {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MONTH, -2);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        return dateToString(cal.getTime(), format);
    }

    /**
     * 获取上上月最后一天
     */
    public static String getLastDayOfLastTwoMonth() {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, cal.get(Calendar.YEAR));
        cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) -1);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        cal.add(Calendar.DAY_OF_MONTH, -1);
        return dateToString(cal.getTime(), DateUtil.LONG_DATE_FORMAT);
    }

    /**
     * 根据提供的年月获取该月份的最后一天
     */
    public static String getSupportEndDayofMonth(int year, int monthOfYear) {
        Calendar cal = Calendar.getInstance();
        // 不加下面2行，就是取当前时间前一个月的第一天及最后一天
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.MONTH, monthOfYear);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        cal.add(Calendar.DAY_OF_MONTH, -1);
        return dateToString(cal.getTime(), DateUtil.LONG_DATE_FORMAT);
    }

    /**
     * 获取指定年月的第一天
     *
     * @param ym yyyy-MM
     * @return
     */
    public static String getFirstDayOfChooseMonth(String ym) {
        String arr[] = ym.split("-");

        int year = Integer.parseInt(arr[0]);
        int month = Integer.parseInt(arr[1]);

        Calendar cal = Calendar.getInstance();
        //设置年份
        cal.set(Calendar.YEAR, year);

        //设置月份
        cal.set(Calendar.MONTH, month - 1);
        //获取某月最小天数
        int firstDay = cal.getMinimum(Calendar.DATE);
        //设置日历中月份的最小天数
        cal.set(Calendar.DAY_OF_MONTH, firstDay);
        //格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        return sdf.format(cal.getTime());
    }

    /**
     * 获取指定年月的最后一天
     *
     * @param ym
     * @return
     */
    public static String getLastDayOfChooseMonth(String ym) {
        String arr[] = ym.split("-");

        int year = Integer.parseInt(arr[0]);
        int month = Integer.parseInt(arr[1]);

        Calendar cal = Calendar.getInstance();
        //设置年份
        cal.set(Calendar.YEAR, year);
        //设置月份
        cal.set(Calendar.MONTH, month - 1);
        //获取某月最大天数
        int lastDay = cal.getActualMaximum(Calendar.DATE);
        //设置日历中月份的最大天数
        cal.set(Calendar.DAY_OF_MONTH, lastDay);
        //格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(cal.getTime());
    }

    /**
     * 将元数据前补零，补后的总长度为指定的长度，以字符串的形式返回
     *
     * @param sourceDate
     * @param formatLength
     * @return 重组后的数据
     */
    public static String addzero(int sourceDate, int formatLength) {
        /*
         * 0 指前面补充零
         * formatLength 字符总长度为 formatLength
         * d 代表为正数。
         */
        String newString = String.format("%0" + formatLength + "d", sourceDate);
        return newString;
    }

    /**
     * 获取现在时间
     *
     * @return 返回短时间字符串格式yyyy-MM-dd HH:mm:ss
     */
    public static String getStringDate(String mdata) {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat(mdata, Locale.CHINA);
        String dateString = formatter.format(currentTime);
        return dateString;
    }

    public static String getYearMonthDay(String netTime) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        ParsePosition pos = new ParsePosition(0);
        Date strtodate = dateFormat.parse(netTime, pos);
        String createDateStr = dateFormat.format(strtodate);
        return createDateStr;
    }

    public static String getYearMonthDayHM(String netTime) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(FORMAT_TWO);
        ParsePosition pos = new ParsePosition(0);
        Date strtodate = dateFormat.parse(netTime, pos);
        String createDateStr = dateFormat.format(strtodate);
        return createDateStr;
    }

    public static String getHM(String netTime) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(FORMAT_FOUR);
        ParsePosition pos = new ParsePosition(0);
        Date strtodate = dateFormat.parse(netTime, pos);
        String createDateStr = dateFormat.format(strtodate);
        return createDateStr;
    }

    public static String getFarmotTime(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }

    public static int getDatediff(String mTvOver) {
        int daynum = 0;
//        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");//显示的时间的格式
        try {
//            Date d1 = df.parse(mTvStart);//得到第一个时间
//            Date d2 = df.parse(mTvOver);//第二个时间
//            long diff = d2.getTime() - d1.getTime();//差值
//
//            long days = diff / (1000 * 60 * 60 * 24);//得到差的天数
//            long hours = (diff - days * (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);//得到差的小时
//            long minutes = (diff - days * (1000 * 60 * 60 * 24) - hours * (1000 * 60 * 60)) / (1000 * 60);//得到差的分钟
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd");//显示的时间的格式

            GregorianCalendar gd = new GregorianCalendar();
            Date dt = gd.getTime();
            Date dt1 = df.parse(mTvOver);//第二个时间
            daynum = (int) ((dt1.getTime() - dt.getTime()) / (24 * 60 * 60 * 1000));

        } catch (ParseException e) {
            e.printStackTrace();
        }
        return daynum;
    }

    /**
     * 获取当前的时间戳
     *
     * @return
     */
    public static String getTimeStame() {
        //获取当前的毫秒值
        long time = System.currentTimeMillis();
        //将毫秒值转换为String类型数据
        String time_stamp = String.valueOf(time);
        //返回出去
        return time_stamp;
    }

    private static final String mformatType = "yyyy-MM-dd HH:mm:ss";

    public static String getFileLastModifiedTime(File file) {
        Calendar cal = Calendar.getInstance();
        long time = file.lastModified();
        SimpleDateFormat formatter = new SimpleDateFormat(mformatType);
        cal.setTimeInMillis(time);

        // 输出：修改时间[2] 2009-08-17 10:32:38
        return formatter.format(cal.getTime());
    }


    /**
     * 获取对应时间戳转换的今天、明天。。。。的日期 * @param time * @return
     */
    public static String getDate(String time) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");// 日期格式
        Calendar pre = Calendar.getInstance();
        Date predate = new Date(System.currentTimeMillis());
        pre.setTime(predate);

        Calendar cal = Calendar.getInstance();
        Date date = null;
        try {
            date = format.parse(time);
        } catch (Exception e) {
            e.printStackTrace();
        }
        cal.setTime(date);

        if (cal.get(Calendar.YEAR) == (pre.get(Calendar.YEAR))) {
            int diffDay = cal.get(Calendar.DAY_OF_YEAR)
                    - pre.get(Calendar.DAY_OF_YEAR);

            return showDateDetail(diffDay, time);
        }

        return getWeekString(time);
    }

    /**
     * 将日期差显示为今天、明天或者星期 * @param diffDay * @param time * @return
     */
    private static String showDateDetail(int diffDay, String time) {
        switch (diffDay) {
            case 0:
                return TODAY;
            case 1:
                return TOMORROW;
            case 2:
                return AFTER_TOMORROW;
            case -1:
                return YESTERDAY;
            case -2:
                return BEFORE_YESTERDAY;
            default:
                return getWeekString(time);
        }
    }

    /**
     * 计算周几
     */
    public static String getWeekString(String data) {
//        String week=null;
        String weekString = null;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");// 日期格式
        try {
            Date date = format.parse(data);
            SimpleDateFormat sdf = new SimpleDateFormat("E");
//            week= sdf.format(date);

            Calendar cd = Calendar.getInstance();
            cd.setTime(new Date(date.getTime()));

            int week = cd.get(Calendar.DAY_OF_WEEK); //获取星期

            switch (week) {
                case Calendar.SUNDAY:
                    weekString = "周日";
                    break;
                case Calendar.MONDAY:
                    weekString = "周一";
                    break;
                case Calendar.TUESDAY:
                    weekString = "周二";
                    break;
                case Calendar.WEDNESDAY:
                    weekString = "周三";
                    break;
                case Calendar.THURSDAY:
                    weekString = "周四";
                    break;
                case Calendar.FRIDAY:
                    weekString = "周五";
                    break;
                default:
                    weekString = "周六";
                    break;

            }
        } catch (ParseException e) {
            e.printStackTrace();
        }


//        if (mydate == 1) {
//            week = "星期日";
//        } else if (mydate == 2) {
//            week = "星期一";
//        } else if (mydate == 3) {
//            week = "星期二";
//        } else if (mydate == 4) {
//            week = "星期三";
//        } else if (mydate == 5) {
//            week = "星期四";
//        } else if (mydate == 6) {
//            week = "星期五";
//        } else if (mydate == 7) {
//            week = "星期六";
//        }
        return data.substring(0, 10) + " " + weekString;
    }

    //根据日期取得星期几
    public static String getWeek(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("E");
        String week = sdf.format(date);
        return week;
    }

    /**
     * 秒转换为时分秒 HH:mm:ss 格式 仅当小时数大于0时 展示HH
     */
    public static String getTimeBySecond(int second) {
        if (second <= 0) {
            return "00:00";
        }
        long h = second / 3600;
        long m = (second % 3600) / 60;
        long s = second % 60;
        String str = "";
        if (h > 0) {
            str = (h < 10 ? ("0" + h) : h) + ":";
        }
        str += (m < 10 ? ("0" + m) : m) + ":";
        str += (s < 10 ? ("0" + s) : s);
        return str;
    }

    /**
     * 秒转换为时分秒 HH:mm:ss 格式 仅当小时数大于0时 展示HH
     */
    public static String getTimeBySecond2(int second) {
        long h = second / 3600;
        long m = (second % 3600) / 60;
        long s = second % 60;
        String str = "";
        str = (h < 10 ? ("0" + h) : h) + ":";
        str += (m < 10 ? ("0" + m) : m) + ":";
        str += (s < 10 ? ("0" + s) : s);
        return str;
    }

    /**
     * 秒转换为时分秒 HH时mm分ss秒 格式 仅当小时数大于0时 展示HH
     */
    public static String getTimeBySecond3(int second) {
        long h = second / 3600;
        long m = (second % 3600) / 60;
        long s = second % 60;
        String str = "";
        if (h > 0) {
            str = (h < 10 ? ("0" + h) : h) + "时";
        }
        str += (m < 10 ? ("0" + m) : m) + "分";
        str += (s < 10 ? ("0" + s) : s) + "秒";
        return str;
    }
}